#!/usr/bin/python
# -*- coding: utf-8 -*-
import db_opt
import jira_opt

# JIRA相关配置
jira_server = 'http://server_addr'
jira_username = 'your_username'
jira_password = 'your_password'

# 查询条件（需要查询的员工账号、查询的JIRA更新时间范围。时间范围包左不包右）
query_users = ['employee_account_1', 'employee_account_2']
query_period = ('2023-12-01', '2024-01-01')

# MySQL数据库配置（需要先创建jira_worklog表，建表语句见“db_opt.sql”）
db_config = {
    'host': 'localhost',
    'port': 3306,
    'schema': 'test',
    'user': 'root',
    'passwd': 'root'
}


def batch_fetch_worklog(client, jql):
    print('JIRA查询语句：', jql)
    fields = ['issuetype', 'status', 'summary', 'created', 'updated', 'reporter', 'creator', 'assignee', 'description', 'worklog']
    has_more = True
    page_no = 0
    page_count = 50
    total_count = 0
    while has_more:
        result = jira_opt.fetch_worklog_list(client, jql, fields, page_no, page_count, query_users)
        page_no += 1
        has_more = result[0]
        if not result[1]:
            continue
        saved_count = db_opt.save_worklog_to_db(db_config, result[1])
        total_count += saved_count
        print('第%s次查询成功保存%s条工作日志' % (page_no, saved_count))
    print('所有操作完成，共计保存/更新了%s条工作日志' % total_count)


if __name__ == "__main__":
    # 创建JIRA客户端
    jira = jira_opt.get_jira_client(jira_server, (jira_username, jira_password))
    # 需要管理员权限才能查询用户组信息，普通用户可查询其他员工工作日志
    # members = jira.group_members('DEV')
    # 组装JIRA JQL语句
    jql = jira_opt.assemble_jql(users=tuple(query_users), period=query_period)
    # 按条件批量查询并保存工作日志
    batch_fetch_worklog(jira, jql)
